<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['config:monitor:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['config:monitor:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" />
      <el-table-column label="监控名称" align="center" prop="name" />
      <el-table-column label="监控类型" align="center" prop="type">
        <template slot-scope="{ row }">
          <dict-tag :options="dict.type.monitor_type" :value="row.type" />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.enabled"
            @change="handleChangeEnabled(row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['config:monitor:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['config:monitor:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改监控配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="监控名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入监控名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            :precision="0"
            v-model="form.sort"
            placeholder="请输入排序"
          />
        </el-form-item>
        <el-form-item label="监控平台" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择">
            <el-option
              v-for="item in dict.type.monitor_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.server">
          <el-form-item label="服务器地址" prop="server.url">
            <el-input
              v-model="form.server.url"
              placeholder="请输入服务器地址"
            />
          </el-form-item>
        </template>
        <template v-if="isDatabaseConfig()">
          <el-form-item label="数据库地址" prop="database.url">
            <el-input
              v-model="form.database.url"
              placeholder="请输入数据库地址"
            />
          </el-form-item>
          <el-form-item label="数据库端口" prop="database.port">
            <el-input
              v-model="form.database.port"
              placeholder="请输入数据库端口"
            />
          </el-form-item>
          <el-form-item label="数据库名" prop="database.dbName">
            <el-input
              v-model="form.database.dbName"
              placeholder="请输入数据库名"
            />
          </el-form-item>
          <el-form-item label="数据库账号" prop="database.username">
            <el-input
              v-model="form.database.username"
              placeholder="请输入数据库账号"
            />
          </el-form-item>
          <el-form-item label="数据库密码" prop="database.password">
            <el-input
              v-model="form.database.password"
              placeholder="请输入数据库密码"
            />
          </el-form-item>
        </template>
        <template v-else-if="form.type === 'prometheus'"> ... </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listConfig,
  getConfig,
  delConfig,
  addConfig,
  updateConfig,
  changeEnabled,
} from "@/api/config/monitor";
import { deepClone } from "@/utils/index";

export default {
  name: "Config",
  dicts: ["monitor_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控配置表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sort: null,
        valid: null,
        enabled: null,
        name: null,
        type: null,
        params: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, trigger: "blur", message: "请输入监控名称" }],
        sort: [{ required: true, trigger: "blur", message: "请输入排序" }],
        type: [
          { required: true, trigger: "change", message: "请选择监控平台" },
        ],
        "server.url": [
          { required: true, trigger: "blur", message: "请输入服务器地址" },
        ],
        "database.url": [
          { required: true, trigger: "blur", message: "请输入数据库地址" },
        ],
        "database.port": [
          { required: true, trigger: "blur", message: "请输入数据库端口" },
        ],
        "database.dbName": [
          { required: true, trigger: "blur", message: "请输入数据库名" },
        ],
        "database.username": [
          { required: true, trigger: "blur", message: "请输入数据库账号" },
        ],
        "database.password": [
          { required: true, trigger: "blur", message: "请输入数据库密码" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询监控配置列表 */
    getList() {
      this.loading = true;
      listConfig(this.queryParams).then((response) => {
        this.configList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sort: 1,
        name: null,
        type: null,
        params: null,
        database: {},
        server: {}
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.names = selection.map((item) => item.name);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监控配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let copyForm = deepClone(row);
      if (this.isDatabaseConfig(copyForm.type)) {
        copyForm.database = JSON.parse(copyForm.params);
        copyForm.server = JSON.parse(copyForm.hostParams);
      }
      this.form = copyForm;
      this.open = true;
      this.title = "修改监控配置";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let copyForm = deepClone(this.form);
          if (this.isDatabaseConfig()) {
            copyForm.params = JSON.stringify(copyForm.database);
          } else {
            copyForm.params = JSON.stringify({});
          }
          copyForm.hostParams = JSON.stringify(copyForm.server);
          delete copyForm.database;
          delete copyForm.server;

          if (this.form.id != null) {
            updateConfig(copyForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(copyForm).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = [row.id] || this.ids;
      this.$modal
        .confirm(
          '是否确认删除监控配置"' + (row.name || this.names) + '"的数据项？'
        )
        .then(function () {
          return delConfig(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/config/export",
        {
          ...this.queryParams,
        },
        `config_${new Date().getTime()}.xlsx`
      );
    },
    handleChangeEnabled(row) {
      changeEnabled({
        id: row.id,
        enabled: row.enabled,
      })
        .then(() => {
          this.$modal.msgSuccess("修改成功");
        })
        .catch(() => {
          row.enabled = !row.enabled;
          this.getList();
        });
    },
    isDatabaseConfig(type) {
      return ["MFO", "zabbix"].includes(type || this.form.type);
    },
  },
};
</script>
